﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;


namespace PowerTriggersService
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }

        private void StartService(string eventName)
        {
            try
            {
                EventLogHelper.LogInformation(eventName + ": Attempting to start service...");
                using (var controller = new ServiceController(this.serviceInstaller1.ServiceName))
                {
                    controller.Start();
                }
            }
            catch (System.Exception ex)
            {
                EventLogHelper.LogError(eventName + " Error", ex);
                throw;
            }
        }

        private void StopService(string eventName)
        {
            try
            {
                using (var controller = new ServiceController(this.serviceInstaller1.ServiceName))
                {
                    switch (controller.Status)
                    {
                        case ServiceControllerStatus.Stopped:
                        case ServiceControllerStatus.StopPending:
                            // do nothing 
                            EventLogHelper.LogInformation(eventName + ": Service already stopped so no need to stop");
                            break;
                        default:
                            // need to attempt a stop
                            EventLogHelper.LogInformation(eventName + ": Attempting to stop service...");
                            controller.Stop();
                            break;
                    }
                }
            }
            catch (InvalidOperationException)
            {
                // this will occur if the service does not exist so just ignore it
            }
            catch (System.Exception ex)
            {
                EventLogHelper.LogError(eventName + " Error", ex);
            }
        }

        private void ProjectInstaller_Committed(object sender, InstallEventArgs e)
        {
            StartService("ProjectInstaller_Committed");
        }

        private void ProjectInstaller_BeforeUninstall(object sender, InstallEventArgs e)
        {
            StopService("ProjectInstaller_BeforeUninstall");
        }

        private void ProjectInstaller_BeforeInstall(object sender, InstallEventArgs e)
        {
            StopService("ProjectInstaller_BeforeInstall");
        }
    }
}
